package dowork;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.util.HashMap;

import javax.imageio.ImageIO;

import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import imageReader.ImagePixelReader;
import imageReader.ImageScale;

public class DrawExcel {
	public void draw(String filePath, String targetPath, String targetWidth) throws IOException {

		XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
		XSSFSheet sheet = xssfWorkbook.createSheet();
		sheet.setDefaultColumnWidth(1);
	

		ImageScale is = new ImageScale();
		BufferedImage image1 = ImageIO.read(new File(filePath));
		int w;
		try {
		w = Integer.parseInt(targetWidth);
		} catch (NumberFormatException e) {
			w = 500;
		}
		BufferedImage image2 = is.imageZoomOut(image1, w, 0, true);

		int height = image2.getHeight();
		int width = image2.getWidth();

		HashMap<String, XSSFCellStyle> styleMap = new HashMap<>();

		for (int i = 0; i < height; i++) {
			XSSFRow row = sheet.createRow(i);
			row.setHeight((short)200);
			for (int j = 0; j < width; j++) {
				int[] rgbInfo = ImagePixelReader.getRGB(image2,  j , i);
				XSSFCellStyle style = null;

				String index = "" + rgbInfo[0] + rgbInfo[1] + rgbInfo[2];
				if (styleMap.containsKey(index)) {
					style = styleMap.get(index);
				} else {
					style = xssfWorkbook.createCellStyle();
					style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
					style.setFillForegroundColor(
							new XSSFColor(new Color(rgbInfo[0], rgbInfo[1], rgbInfo[2]), new DefaultIndexedColorMap()));
					styleMap.put(index, style);
				}				
				XSSFCell cell = row.createCell(j);
				cell.setCellStyle(style);
			}
		}

		FileOutputStream outFile = new FileOutputStream(new File(targetPath+"\\art.xlsx"));
		xssfWorkbook.write(outFile);
		xssfWorkbook.close();
	}
}
